package foliotracker.GUI;

import java.awt.Color;
import java.awt.Graphics;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JPanel;

import foliotracker.Portfolio;
import foliotracker.PortfolioValue;
import foliotracker.views.IPortfolioHistoryView;

public class PortfolioHistoryView extends JPanel implements Observer, IPortfolioHistoryView
{
	private static final long serialVersionUID = 1L;
	private Portfolio portfolio;
	private List<PortfolioValue> values;
	
	public PortfolioHistoryView(Portfolio portfolio)
	{
		this.portfolio = portfolio;
		values = portfolio.getValueHistory();
		Collections.sort(values, new HistoryComparator());
	}
	
	
	@Override
	protected void paintComponent(Graphics g)
	{
		int padding = 40;
		int width = getWidth();
		int height = getHeight();
		long xmin = getXMin();
		long xmax = getXMax();
		double ymax = getYMax();
		
		//draw y axis
		g.drawLine(padding, padding, padding, height - padding);
		
		//draw x axis
		g.drawLine(padding, height - padding, width - padding, height - padding);
		
		g.setColor(Color.BLUE);
		
		//draw points
		List<PortfolioValue> history = portfolio.getValueHistory();
		int x, y, lastX = 0, lastY = 0;
		
		for (int i = 0; i < history.size(); i++)
		{
			PortfolioValue value = history.get(i);
			x = (int)(padding + (value.getDate().getTime() - xmin) / (double)(xmax - xmin) * (width - 2 * padding));
			y = (int)((double)((height - padding) - value.getValue() / ymax * (height - 2 * padding)));

			if (i > 0)
			{
				g.drawLine(lastX, lastY, x, y);
			}
			
			lastX = x;
			lastY = y;
		}
	}
	
	private long getXMin()
	{
		List<PortfolioValue> history = portfolio.getValueHistory();
		
		if (history.size() == 0)
			return 0;
		
		PortfolioValue value = history.get(0);
		return value.getDate().getTime();
	}
	
	
	private long getXMax()
	{
		List<PortfolioValue> history = portfolio.getValueHistory();
		
		if (history.size() == 0)
			return 0;
		
		PortfolioValue value = history.get(history.size() - 1);
		return value.getDate().getTime();
	}
	
	
	private double getYMax()
	{
		double max = 0;
		
		for(PortfolioValue value: portfolio.getValueHistory())
		{
			if (value.getValue() > max)
			{
				max = value.getValue();
			}
		}
		
		return max;
	}
	
	
	private class HistoryComparator implements Comparator<PortfolioValue>
	{
		@Override
		public int compare(PortfolioValue arg0, PortfolioValue arg1)
		{
			return arg0.getDate().compareTo(arg1.getDate());
		}
	}


	@Override
	public void update(Observable arg0, Object arg1)
	{
		this.validate();		
	}
	
	@Override
	public Portfolio getPortfolio()
	{
		return portfolio;
	}
}
